from django.shortcuts import render
from django.shortcuts import render
from django.contrib.auth import login
from django.contrib.auth import logout
from django.contrib.auth import authenticate
from django.shortcuts import reverse
from django.shortcuts import redirect
from xtauth.forms import loginForm


def index_view(request):
    return render(request, 'index.html', locals())


def login_view(request):
    if request.method == 'GET':
        form = loginForm()
        return render(request, 'auth/login.html', locals())
    if request.method == 'POST':
        form = loginForm(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('username')
            password = form.cleaned_data.get('password')
            user = authenticate(username=username, password=password)
            if user is not None:
                login(request, user=user)
                return redirect(reverse('xtauth:index'))
            else:
                return render(request, 'auth/login.html', locals())
        else:
            print(form.errors)


def logout_view(request):
    logout(request)
    return redirect(reverse('xtauth:index'))
